import { deepClone } from '@/utils/helper/jsUtil'

/**
 * 适配器 - 基于不同信源生成通用的信号数据格式
 * 对获取数据进行格式化
 * @param {string} source 信号来源：tsp/车端/云端
 */
function adapterSignalItemData(data, source) {
  if (source === 'vehicleSignal') {
    const item = data.memberList ? data.memberList[0] : {}
    return {
      signalKey: data.key,
      signalName: data.name,
      signalId: data.signalId || data.id,
      interfaceBid: data.interfaceBid,
      serviceBid: data.serviceBid,
      optionalFlag: data.optionalFlag,
      description: data.description,
      symbols: item.symbols || [],
      values: adapterSignalItemDataValues(item.values || []),
      dataType: data.dataType,
      spec: { ...item.dataTypeSpecs, min: item.dataTypeSpecs?.physicalMin ? item.dataTypeSpecs.physicalMin - 0 : -Infinity, max: item.dataTypeSpecs?.physicalMax ? item.dataTypeSpecs.physicalMax - 0 : Infinity }
    }
  } else if (source === 'ecoSignal') {
    return {
      signalKey: data.signalIdentifier,
      signalName: data.name,
      signalId: data.signalId || data.id,
      description: data.description,
      symbols: data.symbols || [],
      values: adapterSignalItemDataValues(data.values || []),
      dataType: data.dataType,
      spec: { ...data.spec, min: data.spec.min ? data.spec.min - 0 : -Infinity, max: data.spec.max ? data.spec.max - 0 : Infinity }
    }
  } else if (source === 'tspSignal') {
    return {
      signalKey: data.signalIdentifier,
      signalName: data.name,
      description: data.description,
      symbols: data.symbols || [],
      values: adapterSignalItemDataValues(data.values || []),
      dataType: data.dataType,
      spec: { ...data.spec, min: data.spec.min ? data.spec.min - 0 : -Infinity, max: data.spec.max ? data.spec.max - 0 : Infinity }
    }
  }
}

function adapterSignalItemDataValues(data) {
  return data.map(el => {
    return {
      name: el.name || '',
      key: el.key
    }
  })
}

function adapterSignalList(data, source) {
  if (source === 'vehicleSignal') {
    return data.map(el => {
      const res = {
        label: el.name,
        value: el.id,
        structChildren: null,
        children: null
      }
      if (el.children) {
        res.children = adapterSignalList(el.children, source)
      }
      if (el.structChildren) {
        res.structChildren = adapterSignalList(el.structChildren, source)
      }
      return res
    })
  } else if (source === 'ecoSignal') {
    return data.map(el => {
      const res = {
        label: el.label,
        value: el.value,
        children: null
      }
      if (el.children) {
        res.children = adapterSignalList(el.children, source)
      }
      return res
    })
  } else if (source === 'tspSignal') {
    return data.map(el => {
      const res = {
        label: el.label,
        value: el.value,
        children: null
      }
      if (el.children) {
        res.children = adapterSignalList(el.children, source)
      }
      return res
    })
  }
}

function adapterSignalItemKey(data, source) {
  if (source === 'vehicleSignal') {
    return data.id
  } else if (source === 'ecoSignal') {
    return data.id
  } else if (source === 'tspSignal') {
    return data.signalIdentifier
  }
}

// 车端信号选择树、以及信号列表，都添加结构体子选项
function addStruct(allData, source) {
  if (source === 'vehicleSignal') {
    const findStructOpiton = (list) => {
      list.forEach(item => {
        if (item.children) {
          findStructOpiton(item.children)
        } else {
          const signal = allData.signals.find(signal => signal.id === item.id)
          if (signal && (signal.dataType === 'Struct' || signal.dataType === 'Array')) {
            item.key = signal.key
            optionAddStruct(item, signal.memberList, signal, allData)
          }
        }
      })
    }
    if (window.vehicleSignal) { // 性能优化，从内存中取格式化好的信号列表
      return window.vehicleSignal
    } else {
      findStructOpiton(allData.options)
      window.vehicleSignal = allData
    }
  }
  return allData
}

// 递归Struct结构体
function optionAddStruct(item, memberList, signal, allData) {
  item.structChildren = []
  memberList && memberList.forEach(member => {
    const newChild = {
      name: member.name,
      signalName: `${item.signalName || item.name}&_&${member.name}`,
      signalId: signal.id,
      key: `${item.key}&_&${member.key}`,
      id: `${item.key}&_&${member.key}`
    }
    item.structChildren.push(newChild)
    if (member.dataType === 'Struct' || member.dataType === 'Array') {
      optionAddStruct(newChild, member.memberList, signal, allData)
    } else {
      const newSignal = deepClone(signal)
      newSignal.name = `${newChild.signalName}`
      newSignal.key = `${newChild.key}`
      newSignal.id = `${newChild.key}`
      newSignal.signalId = signal.id
      newSignal.interfaceBid = signal.interfaceBid
      newSignal.serviceBid = signal.serviceBid
      newSignal.optionalFlag = signal.optionalFlag
      newSignal.dataType = member.dataType
      newSignal.memberList = [{
        symbols: member.symbols,
        values: adapterSignalItemDataValues(member.values || []),
        dataType: member.dataType,
        dataTypeSpecs: member.dataTypeSpecs
      }]
      allData.signals.push(newSignal)
    }
  })
}

function formatSignalList(list) { // 树形数据添加结构体选项
  function findLeaf(list) {
    // 提取叶子节点
    list.forEach(item => {
      if (item.children && item.children.length) {
        findLeaf(item.children)
      } else {
        if (item.structChildren) { // struct结构体逐级解析
          addStructChildren(item)
        }
      }
    })
  }
  findLeaf(list)
  return list
}

// 选择树struct结构体逐级解析（在筛选完最后两级后拼接）
function addStructChildren(curItem) {
  curItem.children = curItem.structChildren
  curItem.structChildren.forEach(child => {
    if (child.structChildren) {
      addStructChildren(child, child.structChildren)
    }
  })
}

function generatorTreeSelectData(signalData) {
  let metaModelId = ''
  if (signalData.signalKey && signalData.signalKey.includes('&_&') && signalData.metaModelId && !signalData.metaModelId.includes('&_&')) { // 初始化结构体数据回显: metaModelId转为前端用的格式
    metaModelId = signalData.signalKey
  } else {
    metaModelId = signalData.metaModelId
  }
  return metaModelId
}

function formatComponentsProp(list) {
  const props = {}
  list.forEach(item => {
    item.props = {}
    const addProp = (prop) => {
      if (prop.fieldType === 'number') {
        prop.defaultValue = prop.defaultValue - 0
      } else if (prop.fieldType === 'boolean') {
        prop.defaultValue = prop.defaultValue === 'true'
      }
      item.props[prop.fieldName] = prop.defaultValue
    }
    item.paramWidgetProperties?.inputParam.forEach(prop => { addProp(prop) })
    item.paramWidgetProperties?.expand.forEach(prop => { addProp(prop) })
    item.props.widgetClassName = item.widgetClassName
    props[item.paramKey[0]] = item.props
  })
  return props
}
export {
  adapterSignalList,
  adapterSignalItemKey,
  adapterSignalItemData,
  formatSignalList,
  addStruct,
  formatComponentsProp,
  generatorTreeSelectData
}
